package com.probiz.estore.product.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

import com.probiz.estore.common.model.product.Product;
import com.probiz.estore.common.model.product.ProductMedia;
import com.probiz.estore.core.service.impl.GenericManagerImpl;
import com.probiz.estore.product.dao.ProductMediaDao;
import com.probiz.estore.product.service.ProductManager;
import com.probiz.estore.product.service.ProductMediaManager;


/**
 * Manager implementation for ProductMedia, responsible for business processing, and communicate between web and persistence layer.
 */
public class ProductMediaManagerImpl extends GenericManagerImpl<ProductMedia> implements ProductMediaManager {

	
	private ProductMediaDao productMediaDao = null;

	/**
	 * @param productMediaDao
	 *            the productMediaDao to set
	 */
	public void setProductMediaDao(ProductMediaDao productMediaDao) {
		this.productMediaDao = productMediaDao;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.service.impl.GenericManagerImpl#init()
	 */
	@Override
	protected void initManager() {
		dao = productMediaDao;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.service.impl.GenericManagerImpl#preDelete(java.lang.Object)
	 */
	@Override
	protected void preDelete(ProductMedia entity) {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.service.impl.GenericManagerImpl#preSave(java.lang.Object)
	 */
	@Override
	protected void preSave(ProductMedia entity) {

	}


	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.service.ProductMediaManager#saveMediasFromArrays(com.probiz.estore.product.model.Product, java.lang.String[], java.lang.String[], java.lang.String[], java.lang.String[])
	 */
	public List<String> saveMediasFromArrays(Product product,String[] mediaIds,String[] mediaUrls,String[] mediaTypes,String[] mediaDescs){
		List<String> newMediaIdList = new ArrayList<String>();
		//删除媒体
		List<String> mediaIdList=Arrays.asList(mediaIds);
		Set<ProductMedia> formerMeidaList=product.getProductMedias();//原来的medias
		for (ProductMedia media : formerMeidaList) {
			if(!mediaIdList.contains(media.getProductMediaId().toString())){
				deleteById(media.getProductMediaId());
			}
		}
		//增加或者修改媒体
		for (int i = 0; i < mediaIds.length; i++) {
			ProductMedia media;
			if(mediaIds[i].equals("")){
				//case:新增
				media = new ProductMedia();
			}else{
				//case:修改
				media = getById(Integer.valueOf(mediaIds[i]));
			}
			media.setMediaUrl(mediaUrls[i]);
			media.setMediaType(Short.valueOf(mediaTypes[i]));
			media.setMediaDescription(mediaDescs[i]);
			media.setSortOrder(i);
			media.setProduct(product);
			save(media);
			newMediaIdList.add(media.getProductMediaId().toString());
		}
		return newMediaIdList;
	}
}
